package cn.portx.policy;

import java.lang.reflect.Field;
import java.util.Date;

import org.springframework.util.Assert;

import com.bstek.bdf3.dorado.jpa.policy.impl.GeneratorPolicy;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;

public class CreatedDatePolicy implements GeneratorPolicy {

	@Override
	public void apply(Object entity, Field field) {
		Assert.isAssignable(Date.class, field.getType(), "Field type must be java.util.Date!");
		boolean isEntity = EntityUtils.isEntity(entity);
		if (isEntity) {
			EntityState state = EntityUtils.getState(entity);
			if (EntityState.NEW.equals(state)) {
				if (EntityUtils.getValue(entity, field.getName()) == null) {
					EntityUtils.setValue(entity, field.getName(), new Date());
				}
			}
		} else {
			field.setAccessible(true);
			try {
				if (field.get(entity) == null) {
					field.set(entity, new Date());
				}
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		}
	}

}
